<template>
  <div>
    <a-spin :spinning="loading">
      <a-button type="primary" @click="creat('creat')">
        <a-icon type="plus"></a-icon>添加跟进记录
      </a-button>
      <div class="record">
        <div class="record_list" v-for="(item,index) in data" :key="index">
          <div class="user_Info">
            <div class="user_headImg">
              <a-avatar icon="user" />
            </div>
            <div class="user_name">{{item.name}}</div>
            <div class="create_time">{{item.created_at|formatDate}}</div>
            <div class="circle_">
              <img src="~@/assets/follow.png" alt />
            </div>
          </div>
          <div class="record_content">
            <div class="content_text">
              {{item.content}}
              <div class="action" v-if="item.type==1">
                <a-icon
                  type="edit"
                  style="cursor:pointer;margin-right:10px;"
                  @click="getInfo(item.id)"
                />
                <a-popconfirm
                  overlayClassName="studentInfo_followUpDel"
                  title="确认删除？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="del(item.id)"
                >
                  <a-icon type="delete" style="cursor:pointer" />
                </a-popconfirm>
              </div>
            </div>
            <div class="content_imgs" v-if="item.img">
              <div class="imgList" v-for="(j,k) in item.img" :key="k" @click="lookImg(j)">
                <img :src="j" alt />
              </div>
            </div>
            <div class="nextFollowTime" v-if="item.next_time">
              <a-icon type="history" />
              下次跟进：{{item.next_time|formatDate}}
            </div>
            <div class="nextFollowTime" v-else>暂无下次跟进时间</div>
          </div>
        </div>
        <div class="page" v-if="data.length>1">
          <a-pagination
            v-model="current"
            show-size-changer
            :page-size.sync="pageSize"
            :total="total"
            @showSizeChange="onShowSizeChange"
          />
        </div>
      </div>
      <a-modal
        :visible="creat_visible"
        :title="visibleType=='creat'?'添加跟进记录':'编辑跟进记录'"
        @ok="sure"
        @cancel="creat_visible=false"
        :confirmLoading="btnLoading"
      >
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-model-item label="跟进内容" prop="content">
            <a-textarea
              v-model="form.content"
              placeholder="请输入跟进内容"
              :maxLength="1000"
              :auto-size="{ minRows: 3, maxRows: 5 }"
            />
            <a-form-model-item aria-label=" " :colon="false">
              <a-upload
                :before-upload="beforeUpload"
                list-type="picture-card"
                :file-list="fileList"
                :remove="removePic"
              >
                <div v-if="fileList.length < 9">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">上传图片</div>
                </div>
              </a-upload>
            </a-form-model-item>
            <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
              <img alt="example" style="width: 100%" :src="previewImage" />
            </a-modal>
          </a-form-model-item>
          <a-form-model-item label="下次跟进">
            <a-date-picker
              v-model="time"
              show-time
              format="YYYY-MM-DD HH:mm"
              placeholder="选择时间"
              @change="changeTime"
              :disabled-date="disabledDate"
            />
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </a-spin>
    <a-modal :visible="showImgModal" @cancel="showImgModal=false" :footer="null">
      <div class="imgModal">
        <img :src="imgModal" alt />
      </div>
    </a-modal>
  </div>
</template>

<script>
import { studentFollow, studentFollowDel, studentFollowAdd, studentFollowInfo, studentFollowEdit } from '@/api/student'
import { uploadPic } from '@/api/login'
import moment from 'moment'
// import formatDate from '@/utils/filter'
export default {
  name: 'followUp',
  props: ['studentId'],
  data() {
    return {
      loading: false,
      btnLoading: false,
      data: [],
      pageSize: 20,
      current: 1,
      total: null,
      creat_visible: false,
      form: {
        content: '',
        time: '',
      },
      rules: {
        content: [{ required: true, message: '请输入跟进内容', trigger: 'blur' }],
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      previewVisible: false,
      previewImage: '',
      fileList: [],
      visibleType: '',
      time: undefined,
      imgModal: '',
      showImgModal: false,
    }
  },
  created() {
    this.getList()
  },
  watch: {
    pageSize(val) {},
    current(val) {},
    creat_visible(val) {
      if (val == false) {
        this.previewVisible = false
        this.previewImage = ''
        this.fileList = []
        this.visibleType = ''
        this.form = {
          content: '',
          time: '',
        }
        this.time = undefined
        this.btnLoading = false
      }
    },
    showImgModal(val) {
      if ((val = false)) {
        this.imgModal = ''
      }
    },
  },
  methods: {
    disabledDate(current) {
      return current && current < moment().startOf('day')
    },
    getInfo(e) {
      this.visibleType = 'edit'
      studentFollowInfo(e).then((res) => {
        this.form.content = res.content
        this.time = moment(this.formatDate(res.created_at))
        this.form.time = this.formatDate(res.created_at)
        this.form.id = e
        if (res.img && res.img.length > 0) {
          res.img.forEach((val) => {
            this.fileList.push({
              name: val,
              uid: this.fileList.length + 1,
              url: val,
            })
          })
        }
        this.creat_visible = true
      })
    },
    getList() {
      this.loading = true
      studentFollow({ student_id: this.studentId }).then((res) => {
        this.data = res.data
        this.per_page = res.meta.pagination.pageSize
        this.total = res.meta.pagination.total
        this.loading = false
      })
    },
    onShowSizeChange(current, pageSize) {},
    del(e) {
      studentFollowDel(e)
        .then((res) => {
          this.$message.success('删除成功')
          this.getList()
        })
        .catch((err) => {
          this.$message.error(err.data.message || '删除失败')
        })
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/svg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif'
      if (!isJpgOrPng) {
        this.$message.error('只能上传jpg/png图片格式！')
        return
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('只能上传10MB以内的图片!')
        return
      }
      const _this = this
      const formData = new FormData()
      formData.append('file', file)
      formData.append('school_id', this.$store.state.user.school)
      this.btnLoading = true
      uploadPic(formData)
        .then((res) => {
          this.fileList.push({
            name: res.path,
            uid: this.fileList.length + 1,
            url: res.url,
          })
          this.btnLoading = false
        })
        .catch((err) => {
          this.btnLoading = false
          this.$message.error(err.data.message || '上传失败，请稍后重试~')
        })
      return false
    },
    handleCancel() {
      this.previewVisible = false
    },
    removePic(a) {
      this.fileList.forEach((item, index) => {
        if (item.uid == a.uid) {
          this.fileList.splice(index, 1)
        }
      })
    },
    creat(e) {
      this.creat_visible = true
      this.visibleType = e
    },
    sure() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true
          let params = JSON.parse(JSON.stringify(this.form))
          params.student_id = this.studentId
          params.img = []
          if (this.time) {
            params.next_time = this.time.format('YYYY-MM-DD HH:mm')
          }
          this.fileList.forEach((val) => {
            params.img.push(val.url)
          })
          if (this.visibleType === 'creat') {
            studentFollowAdd(params)
              .then((res) => {
                this.$message.success('添加成功')
                this.creat_visible = false
                this.btnLoading = false
                this.getList()
              })
              .catch((err) => {
                this.$message.error(err.data.message || '添加失败，请稍后重试')
                this.btnLoading = false
              })
          } else {
            studentFollowEdit(params, params.id)
              .then((res) => {
                this.$message.success('修改成功')
                this.creat_visible = false
                this.btnLoading = false
                this.getList()
              })
              .catch((err) => {
                this.$message.error(err.data.message || '修改失败，请稍后重试')
                this.btnLoading = false
              })
          }
        } else {
          return false
        }
      })
    },
    changeTime(date, dateString) {
      this.form.time = dateString
    },
    lookImg(e) {
      this.imgModal = e
      this.showImgModal = true
    },
    formatDate(value) {
      let date = new Date(value * 1000)
      let y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? '0' + MM : MM
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      let h = date.getHours()
      h = h < 10 ? '0' + h : h
      let m = date.getMinutes()
      m = m < 10 ? '0' + m : m
      let s = date.getSeconds()
      s = s < 10 ? '0' + s : s
      return y + '-' + MM + '-' + d + ' ' + h + ':' + m
    },
  },
}
</script>
<style lang="less">
.studentInfo_followUpDel {
  .ant-popover-content {
    .ant-popover-inner {
      padding: 10px !important;
    }
  }
}
</style>
<style lang="less" scoped>
.imgModal {
  margin-top: 20px;
  width: 470px;
  text-align: center;
  height: auto;
  max-height: 500px;
  overflow: hidden;
  img {
    width: 100%;
    height: auto;
    overflow: hidden;
  }
}
.record {
  padding: 20px;
  .record_list {
    display: flex;
    .user_Info {
      width: 180px;
      text-align: center;
      height: auto;
      border-right: 1px solid #ccc;
      padding-bottom: 60px;
      position: relative;
      div {
        padding: 2px 0;
      }
      .create_time {
        color: rgb(153, 153, 153);
      }
      .circle_ {
        position: absolute;
        right: -12.2px;
        top: 10px;
        img {
          width: 24px;
          height: 24px;
        }
      }
    }
    .record_content {
      margin-bottom: 10px;
      padding-top: 10px;
      margin-left: 50px;
      .content_text {
        width: 825px;
        overflow-x: auto;
        padding: 10px;
        padding-right: 50px;
        max-height: 100px;
        background: #ebebec;
        position: relative;
        .action {
          position: absolute;
          width: 50px;
          right: 0;
          top: 10px;
          align-items: center;
        }
      }
      .content_imgs {
        margin-top: 10px;
        display: flex;
        .imgList {
          width: 60px;
          height: 60px;
          text-align: center;
          line-height: 60px;
          margin-right: 10px;
          overflow: hidden;
          img {
            width: 100%;
            height: auto;
            overflow: hidden;
          }
        }
      }
      .nextFollowTime {
        padding: 0 10px 0 0px;
        margin-top: 20px;
        color: rgb(144, 144, 144);
      }
    }
  }
  .record_list:first-child {
    .record_content {
      margin-top: 0px;
      padding-top: 5px;
    }
  }
  .page {
    margin-top: 20px;
    text-align: right;
  }
}
</style>